#include "graphtab.h"
#include "ui_graphtab.h"

#include "cashplusplus.h"

GraphTab::GraphTab(QWidget *parent) :
	Tab(parent),
	m_ui(new Ui::GraphTab)
{
	m_ui->setupUi(this);

	m_accountModel = 0;
}

GraphTab::~GraphTab()
{
	delete m_ui;
}

void GraphTab::updateContents()
{
	initializeModel();
}

void GraphTab::flushData()
{
}

void GraphTab::cleanup()
{
	if (m_accountModel)
	{
		delete m_accountModel;
		m_accountModel = 0;
	}
}

void GraphTab::initializeModel()
{
	m_accountModel = new AccountModel(this);
	m_accountModel->setSort(1, Qt::AscendingOrder);

	m_ui->accountFilter->setModel(m_accountModel);
	m_ui->accountFilter->setModelColumn(1);

	disableButtonsIfNecessary();
}

void GraphTab::changeEvent(QEvent *e)
{
	QWidget::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		m_ui->retranslateUi(this);
		break;
	default:
		break;
	}
}

int GraphTab::currentAccount() const
{
	return m_ui->accountFilter->model()->index(m_ui->accountFilter->currentIndex(), 0).data().toInt();
}

void GraphTab::on_accountFilter_currentIndexChanged(int)
{
	disableButtonsIfNecessary();

	QSqlQuery q(QSqlDatabase::database(CashPlusPlus::DB_NAME));

	int account = currentAccount();

	q.prepare("SELECT SUM(amount) FROM transactions WHERE account_id = ?");
	q.addBindValue(account);
	q.exec();
	q.next();
	double transactionTotal = q.value(0).toDouble();

	q.prepare("SELECT amount FROM accounts WHERE id = ?");
	q.addBindValue(account);
	q.exec();
	q.next();
	double total = q.value(0).toDouble() - transactionTotal;

	q.prepare("SELECT datetime, amount FROM transactions WHERE account_id = ? ORDER BY datetime ASC");
	q.addBindValue(account);
	q.exec();

	QList<QPair<uint, double> > list;

	while(q.next())
	{
		total += q.value(1).toDouble();
		list.append(QPair<uint, double>(q.value(0).toUInt(), total));
	}

	m_ui->graphWidget->setData(list);
}

void GraphTab::disableButtonsIfNecessary()
{
	bool haveAccounts = m_ui->accountFilter->count() > 0;
	m_ui->accountFilter->setEnabled(haveAccounts);
}
